﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using DAL;

namespace PeisongWeb.admin
{
    public partial class reorderList : adminPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (hasPermission("DB", 1))
                {
                    rptBind();
                }
                else
                {
                    Library.Script.ClientMsgUrl("没有权限！", "index.aspx");
                    return;
                }

            }
        }
        /// <summary>
        /// 详细信息中的订单状态
        /// </summary>
        private void drpBind()
        {
            ddl_Status.DataSource = logic.sysCode.orderStatus();
            ddl_Status.DataBind();

            ddl_receiveTime.DataSource = logic.sysCode.receiveTime();
            ddl_receiveTime.DataBind();
        }
        void rptBind()
        {
            int customerId = logic.customer.userId;
            StringBuilder where = new StringBuilder();
            where.Append("source=4 and status ='1'");
            if (txt_orderNo.Text.Trim() != "")
                where.AppendFormat(" and orderNo = '{0}'", txt_orderNo.Text.Trim());
            if (ext_StartInputDt.SelectedDate != DateTime.MinValue)
                where.AppendFormat(" and datediff(day,[orderDt],'{0}')<=0", ext_StartInputDt.Value.ToString());
            if (ext_EndInputDt.SelectedDate != DateTime.MinValue)
                where.AppendFormat(" and datediff(day,[orderDt],'{0}')>=0", ext_EndInputDt.Value.ToString());
            DataSet ds = logic.order.select(where.ToString(), "orderid desc", AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex);
            AspNetPager1.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
            rpt_list.DataSource = ds.Tables[1];
            rpt_list.DataBind();
        }
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            rptBind();
        }

        //订单列表中的搜索
        protected void btn_select_Click(object sender, EventArgs e)
        {
            rptBind();
        }

        //查看详细信息
        protected void rpt_list_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "details")
            {
                int id = Convert.ToInt32(e.CommandArgument);
                drpBind();
                getDetails(id);
            }
        }
        private void getDetails(int orderid)
        {
            hd_orderid.Value = orderid.ToString();
            DataSet ds = logic.order.select("orderid=" + orderid, "orderid", 1, 1);
            DataRow dr = ds.Tables[1].Rows[0];
            hd_customerid.Value = dr["customerid"].ToString();
            lbl_OrderNo.Text = "订单编号：" + dr["orderNo"].ToString();
            if (dr["source"].ToString() == "1")         //订单来源为网站订单就显示用户名，电话订单就显示录入者
            {
                lbl_user.InnerText = "用户名：";
                lbl_username.Text = dr["username"].ToString();
            }
            else
            {
                lbl_user.InnerText = "录入者：";
                lbl_username.Text = logic.sysAdmin.getById(Convert.ToInt32(dr["customerid"])).Username;
            }
            lbl_orderSource.Text = dr["sourceName"].ToString();     // 订单来源：1、网站订单；2、电话订单
            lbl_orderDt.Text = dr["orderDt"].ToString();            // 下单日期
            ext_receiveDt.SelectedDate = Convert.ToDateTime(dr["receiveDt"]);        //收货日期

            string time = Convert.ToDateTime(dr["receiveDt"]).Hour - 1 + ":00" + "-" + Convert.ToDateTime(dr["receiveDt"]).ToShortTimeString();

            ListItem c = ddl_receiveTime.Items.FindByText(time);

            if (c != null)
            {
                c.Selected = true;
            }
            lbl_Note.Text = dr["note"].ToString();          //订单中的客户备注
            txt_Amount.Value = String.Format("{0:F2}", dr["Amount"]).ToString();    //支付总价
            txt_serviceNote.Text = dr["serviceNote"].ToString();                    //客服备注
            lbl_StandardAmount.Text = String.Format("{0:F2}", dr["standardAmount"]).ToString(); //汇总总价(不算运费和税费)
            ddl_Status.SelectedValue = dr["status"].ToString();         //订单状态
            txt_closeReason.Text = dr["closeReason"].ToString();        //交易关闭原因
            lbl_company.Text = dr["company"].ToString();                //采购商公司名称
            lbl_contact.Text = dr["contact"].ToString();                //联系人
            lbl_contactMobile.Text = dr["contactMobile"].ToString();    //公司联系电话
            lbl_contactPhone.Text = dr["contactPhone"].ToString();          //联系人手机
            lbl_Address.Text = dr["areaName"].ToString() + dr["address"].ToString();    //收货地址
            hd_companyid.Value = dr["companyId"].ToString();                    //采购商ID
            //if (Convert.ToInt32(dr["status"]) == 4 || Convert.ToInt32(dr["status"]) == 5)   //如果订单是 交易成功 和 交易关闭 状态，就不能修改订单信息
            //{        
            //    btn_UpdateStatus.Visible = false;
            //}
            //else
            //{
            //    btn_UpdateStatus.Visible = true;
            //}
            bind(orderid);
            lbl_Total.Text = String.Format("{0:F2}", dr["standardAmount"]);     //订单细目中的汇总价格

            //if (dr["status"].ToString() != "5")
            //{
            //    a_print.HRef = "reportcustomerdetail.aspx?rb=&order=" + dr["orderNo"].ToString();
            //    a_print.Visible = true;
            //}
            //else
            //    a_print.Visible = false;

            order_details.Show();
        }

        //修改订单信息和订单细目中的商品数量
        protected void btn_Save_Click(object sender, EventArgs e)
        {
            int orderid = Convert.ToInt32(hd_orderid.Value);
            OrderEntity _order = new OrderEntity();
            _order.Orderid = orderid;
            _order.StandardAmount = Math.Round(Convert.ToDecimal(lbl_StandardAmount.Text),2, MidpointRounding.AwayFromZero);     //汇总总价
            _order.Amount = Convert.ToDecimal(lbl_StandardAmount.Text);
            _order.FireightFee = 0;
            _order.Taxfee = 0;
            _order.Status = ddl_Status.SelectedValue;                //订单状态
            _order.ServiceNote = txt_serviceNote.Text;               //客服备注
            string timeRange = ddl_receiveTime.SelectedItem.Text;
            int hour = Convert.ToInt32(timeRange.Substring(timeRange.IndexOf("-") + 1, timeRange.Length - (timeRange.IndexOf("-") + 4)));
            _order.ReceiveDt = Convert.ToDateTime(ext_receiveDt.Value).AddHours(hour);    //收货时间

            _order.CloseReason = txt_closeReason.Text;              //交易关闭
            _order.AdminId = logic.sysAdmin.AdminID;                 //操作者ID

            for (int i = 0; i < rpt_OrderItems.Items.Count; i++)    //修改商品细目表
            {
                RepeaterItem row = rpt_OrderItems.Items[i];
                HiddenField hid = row.FindControl("hid_oiId") as HiddenField;
                TextBox txt = row.FindControl("txtQuantity") as TextBox;
                TextBox txtNote = row.FindControl("txtCustomerNote") as TextBox;

                int oiid = Convert.ToInt32(hid.Value);
                decimal quantity = Convert.ToDecimal(txt.Text);
                logic.orderItem.updateQuantity(oiid, quantity, txtNote.Text);      //根据细目ID 和 商品数量 修改
            }
            logic.order.update(_order);
            Library.Script.ClientMsg("修改成功！");
            rptBind();
            //getDetails(orderid);
        }

        //删除商品
        protected void rpt_OrderItems_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Del")
            {
                int oiid = Convert.ToInt32(e.CommandArgument);
                logic.orderItem.delete(oiid);
                Library.Script.ClientMsg("删除成功！");
                int orderid = Convert.ToInt32(hd_orderid.Value);
                getDetails(orderid);
            }
        }

        /// <summary>
        /// 绑定所选择的订单下的商品信息
        /// </summary>
        /// <param name="orderid"></param>
        void bind(int orderid)
        {
            rpt_OrderItems.DataSource = logic.orderItem.select("orderId=" + orderid, "oiId", 100, 1).Tables[1];
            rpt_OrderItems.DataBind();
        }

        //显示所有商品信息
        protected void lbn_Add_Click(object sender, EventArgs e)
        {
            categoryRootBind();
            categorySubBind();
            rptProBind();
        }

        //订单详细信息中的搜索
        protected void lbn_search_Click(object sender, EventArgs e)
        {
            rptProBind();
        }

        //绑定在采购商的采购范围中的商品
        void rptProBind()
        {
            StringBuilder where = new StringBuilder();
            where.Append("categoryIsShow=1");
            if (ddl_CategoryRoot.SelectedValue != "")
                where.AppendFormat(" and categoryParentId={0}", ddl_CategoryRoot.SelectedValue);
            if (ddl_CategorySub.SelectedValue != "")
                where.AppendFormat(" and categoryId={0}", ddl_CategorySub.SelectedValue);
            if (txt_ProductNo.Text.Trim() != "")
                where.AppendFormat(" and productNo like '%{0}%'", txt_ProductNo.Text.Trim());
            if (txt_ProductName.Text.Trim() != "")
                where.AppendFormat(" and [Name] like '%{0}%'", txt_ProductName.Text.Trim());
            DataSet ds = logic.product.select(where.ToString(), "productId", AspNetPager2.PageSize, AspNetPager2.CurrentPageIndex);
            //DataSet ds = logic.product.listWithCurrentPrice(Convert.ToInt32(hd_companyid.Value),
            //    where.ToString(), "productId", AspNetPager2.PageSize, AspNetPager2.CurrentPageIndex);
            AspNetPager2.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
            rpt_Products.DataSource = ds.Tables[1];
            rpt_Products.DataBind();
            product_add.Show();
        }
        protected void AspNetPager2_PageChanged(object sender, EventArgs e)
        {
            rptProBind();
        }

        /// <summary>
        /// 根据采购商的采购范围绑定大类
        /// </summary>
        void categoryRootBind()
        {
            int companyId = Convert.ToInt32(hd_companyid.Value);
            ddl_CategoryRoot.DataSource = logic.category.listWithCompanyRange(companyId);
            ddl_CategoryRoot.DataBind();
        }

        /// <summary>
        /// 根据大类得到小类
        /// </summary>
        void categorySubBind()
        {
            DataTable dt = logic.category.getByParent(Convert.ToInt32(ddl_CategoryRoot.SelectedValue));
            ddl_CategorySub.DataSource = dt;
            ddl_CategorySub.DataBind();
        }
        protected void ddl_CategoryRoot_SelectedIndexChanged(object sender, EventArgs e)
        {
            categorySubBind();
        }

        //添加商品
        protected void lbn_AddOrderItem_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < rpt_Products.Items.Count; i++)      //循环Repeater
            {
                RepeaterItem row = rpt_Products.Items[i];
                HiddenField hidproId = row.FindControl("hid_productId") as HiddenField;
                Label lblproName = row.FindControl("lbl_proName") as Label;
                TextBox lblsellerPrice = row.FindControl("txt_Price") as TextBox;  //供应价
                TextBox txtBuyPrice = row.FindControl("txt_BuyPrice") as TextBox;  //购买价格
                TextBox txtQuantity = row.FindControl("txtQuantity") as TextBox;
                TextBox txtnote = row.FindControl("txtNote") as TextBox;
                TextBox txtUnit = row.FindControl("lbl_unit") as TextBox;
                CheckBox cbxSelect = row.FindControl("cbx_isSelect") as CheckBox;
                if (cbxSelect.Checked)            //找到选择的商品加入数据库
                {
                    OrderItemEntity oi = new OrderItemEntity();
                    oi.CustomerId = Convert.ToInt32(hd_customerid.Value);
                    oi.Note = txtnote.Text; ;
                    oi.OrderId = Convert.ToInt32(hd_orderid.Value);
                    oi.Price = Convert.ToDecimal(txtBuyPrice.Text);
                    oi.ProductId = Convert.ToInt32(hidproId.Value);
                    oi.Quantity = Convert.ToDecimal(txtQuantity.Text);
                    oi.InitQuantity = oi.Quantity;
                    oi.SellerId = 146;
                    oi.SellerPrice = Convert.ToDecimal(lblsellerPrice.Text.Trim());
                    oi.Unit = logic.product.getById(oi.ProductId).Unit;
                    logic.orderItem.update(oi);
                }
            }
            int orderid = Convert.ToInt32(hd_orderid.Value);
            rptBind();
            getDetails(orderid);
        }
        protected void lbl_cancel_Click(object sender, EventArgs e)
        {
            int orderid = Convert.ToInt32(hd_orderid.Value);
            product_add.Close();
            getDetails(orderid);
        }
        protected void lbtn_Search_Click(object sender, EventArgs e)
        {
            rptBind();
        }

        protected void btn_UpdateStatus_Click(object sender, EventArgs e)
        {
            int orderid = Convert.ToInt32(hd_orderid.Value);
            OrderEntity _order = new OrderEntity();
            _order.Orderid = orderid;
            _order.Status = ddl_Status.SelectedValue;
            logic.order.updateStatus(_order);
            Library.Script.ClientMsg("修改状态成功！");
            rptBind();
        }
        [Coolite.Ext.Web.AjaxMethod]
        public string orderList_getDetails(int productid)
        {
            DataTable dt = logic.files.getListByProduct(productid);
            return Library.Resource.UploadPath + Library.Resource.FileThumbnail1 + "/" + dt.Rows[0]["systemName"].ToString();

        }
    }
}
